package com.vc.videosdk

import android.graphics.BitmapFactory
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.vc.videosdk.bean.ReqAppRoot
import com.vc.videosdk.bean.ReqClipboard
import com.vc.videosdk.bean.ReqStartApp
import com.vc.videosdk.bean.ReqStopApp
import com.vc.videosdk.bean.ReqSysDpi
import com.vc.videosdk.bean.ReqSysPreviewStart
import com.vc.videosdk.bean.ReqSysResolution
import com.vc.videosdk.bean.ReqSysRoot
import com.vc.videosdk.bean.ReqUnInstallApp
import com.vc.videosdk.bean.ReqVirtualLocation
import com.vc.videosdk.custom.OperatorListener
import com.vc.videosdk.custom.PreviewOperatorListener
import com.vc.videosdk.interfaces.PreviewConnectListener
import com.vc.videosdk.interfaces.WebSocketConnectListener
import com.vc.videosdk.message.MessageInfo
import com.vc.videosdk.message.MessageInfo2
import com.vc.videosdk.message.MessageResult
import com.vc.videosdk.utils.RequestIdCreatUtil
import com.vc.videosdk.xlog.XLogUtil
import org.java_websocket.WebSocketImpl
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.nio.ByteBuffer
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.ConcurrentHashMap


/**

 * @Author : wy

 * @Time : On 2024/9/14 14:16

 * @Description : VcOperateManager 提供给三方应用调用

 */
class VcOperateManager private constructor() {
    private val TAG="VcOperateManager_"
    private val TAG_ERROR="VcOperateManager_Error_"
    private var mTimerSendHeartBeat: Timer? = null
    private var mDeviceId="device_id_123456789"
    val mOperatorInstanceIdMap =
        ConcurrentHashMap<String, ConcurrentHashMap<String, OperatorListener>>()

    companion object {
        private var singleInstance: VcOperateManager? = null
            get() {
                // 懒汉模式
                if (null == field) {
                    field = VcOperateManager()
                }
                return field
            }

        @Synchronized // 添加注解，线程同步，线程安全
        fun getInstance(): VcOperateManager {
            return singleInstance!! // 表示非空时执行
        }
    }


    /**
     * 启动应用
     */
    fun startApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        packageName: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val reqStartApp = ReqStartApp(packageName)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.START_APP),
                    Constant.START_APP,
                    reqStartApp
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))


                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.START_APP, listener)
            }
            return
        }



        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val reqStartApp = ReqStartApp(packageName)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.START_APP),
                                Constant.START_APP,
                                reqStartApp
                            )

                            XLogUtil.d("${TAG}startApp() sendMessage clientConnect:$webSocketClient")
                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}startApp() sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.START_APP, message)
                    XLogUtil.d(
                        "${TAG}startApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )

                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false


                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}startApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    isSendResult = false
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}startApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false

                }
            })!!

    }


    /**
     * 停止应用
     */
    fun stopApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        packageName: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null

        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val reqStopApp = ReqStopApp(packageName)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.STOP_APP),
                    Constant.STOP_APP,
                    reqStopApp
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.STOP_APP, listener)
            }
            return
        }



        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token,getDeviceId(), object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val reqStopApp = ReqStopApp(packageName)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.STOP_APP),
                                Constant.STOP_APP,
                                reqStopApp
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}stopApp() sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.STOP_APP, message)
                    XLogUtil.d(
                        "${TAG}stopApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}stopApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}stopApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })!!

    }


    /**
     * 卸载应用
     */
    fun unInstallApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        packageName: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val reqUnInstallApp = ReqUnInstallApp(packageName)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.UN_INSTALL_APP),
                    Constant.UN_INSTALL_APP,
                    reqUnInstallApp
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.UN_INSTALL_APP, listener)
            }
            return
        }


        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token,getDeviceId(), object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val reqUnInstallApp = ReqUnInstallApp(packageName)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.UN_INSTALL_APP),
                                Constant.UN_INSTALL_APP,
                                reqUnInstallApp
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}unInstallApp() sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.UN_INSTALL_APP, message)
                    XLogUtil.d(
                        "${TAG}unInstallApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false

                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}unInstallApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}unInstallApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 隐藏应用
     */
    fun hideApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val messageInfo = MessageInfo2(
                    RequestIdCreatUtil.creatId(Constant.HIDE_APP),
                    Constant.HIDE_APP
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.HIDE_APP, listener)
            }
            return
        }


        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {

                            val messageInfo = MessageInfo2(
                                RequestIdCreatUtil.creatId(Constant.HIDE_APP),
                                Constant.HIDE_APP
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}hideApp sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.HIDE_APP, message)
                    XLogUtil.d(
                        "${TAG}hideApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false

                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}hideApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}hideApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 显示应用
     */
    fun displayApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val messageInfo = MessageInfo2(
                    RequestIdCreatUtil.creatId(Constant.DISPLAY_APP),
                    Constant.DISPLAY_APP,
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.DISPLAY_APP, listener)
            }
            return
        }

        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val messageInfo = MessageInfo2(
                                RequestIdCreatUtil.creatId(Constant.DISPLAY_APP),
                                Constant.DISPLAY_APP,
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}displayApp sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.DISPLAY_APP, message)
                    XLogUtil.d(
                        "${TAG}displayApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false

                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}displayApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}displayApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 应用root
     */
    fun rootApp(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        rootSwitch: Int,
        packageList: List<String>,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null

        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val reqAppRoot = ReqAppRoot(rootSwitch, packageList)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.APP_ROOT),
                    Constant.APP_ROOT,
                    reqAppRoot
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.APP_ROOT, listener)
            }
            return
        }



        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val reqAppRoot = ReqAppRoot(rootSwitch, packageList)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.APP_ROOT),
                                Constant.APP_ROOT,
                                reqAppRoot
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}rootApp sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.APP_ROOT, message)
                    XLogUtil.d(
                        "${TAG}rootApp 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false

                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}rootApp connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false

                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}rootApp onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 全局root
     */
    fun systemRoot(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        rootSwitch: Int,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val reqSysRoot = ReqSysRoot(rootSwitch)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.SYS_ROOT),
                    Constant.SYS_ROOT,
                    reqSysRoot
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.SYS_ROOT, listener)
            }
            return
        }

        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val reqSysRoot = ReqSysRoot(rootSwitch)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.SYS_ROOT),
                                Constant.SYS_ROOT,
                                reqSysRoot
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}systemRoot sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYS_ROOT, message)
                    XLogUtil.d(
                        "${TAG}systemRoot 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false

                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}systemRoot connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}systemRoot onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })
    }


    /**
     * 开启预览图推流
     * ● interval：预览图推流间隔时间，类型为 string。单位为秒
     * ● width：预览图宽，类型为 string
     * ● height：预览图高，类型为 string
     * ● quality：预览图质量，类型为 string 值范围： 1-100
     */
    @OptIn(ExperimentalStdlibApi::class)
    fun sysPreviewStart(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        interval: String,
        width: String,
        height: String,
        quality: String,
        listener: PreviewOperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null

        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : PreviewConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val sysPreviewStart =
                                ReqSysPreviewStart(interval, width, height, quality)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.SYSTEM_PREVIEW_START),
                                Constant.SYSTEM_PREVIEW_START,
                                sysPreviewStart
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                            //发送心跳
                           // openHeartBeatSend(webSocketClient)
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}sysPreviewStart sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYSTEM_PREVIEW_START, message)
                    XLogUtil.d(
                        "${TAG}sysPreviewStart 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )

                    if (isSendResult) {
                        listener.operatorResult(
                            instanceId,
                            result.code,
                            result.type,
                            result.message
                        )
                    } else if (result.type == Constant.SYSTEM_PREVIEW_STOP) {
                        listener.operatorResult(
                            instanceId,
                            result.code,
                            result.type,
                            result.message
                        )
                        clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    } else if (result.type == Constant.START_APP) {
                        //获取实例对应的operatorListener,将结果回调给客户
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.START_APP)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.START_APP)
                        }
                    } else if (result.type == Constant.STOP_APP) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.STOP_APP)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.STOP_APP)
                        }
                    } else if (result.type == Constant.UN_INSTALL_APP) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.UN_INSTALL_APP)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.UN_INSTALL_APP)
                        }
                    } else if (result.type == Constant.HIDE_APP) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.HIDE_APP)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.HIDE_APP)
                        }
                    } else if (result.type == Constant.DISPLAY_APP) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.DISPLAY_APP)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.DISPLAY_APP)
                        }
                    } else if (result.type == Constant.APP_ROOT) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.APP_ROOT)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.APP_ROOT)
                        }
                    } else if (result.type == Constant.SYS_ROOT) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.SYS_ROOT)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.SYS_ROOT)
                        }
                    } else if (result.type == Constant.VIRTUAL_LOCATION) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.VIRTUAL_LOCATION)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.VIRTUAL_LOCATION)
                        }
                    } else if (result.type == Constant.SYSTEM_RESOLUTION) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.SYSTEM_RESOLUTION)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.SYSTEM_RESOLUTION)
                        }
                    } else if (result.type == Constant.SYSTEM_DPI) {
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.SYSTEM_DPI)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.SYSTEM_DPI)
                        }
                    } else if (result.type == Constant.SYSTEM_CLIP_BOARD) {
                        //获取实例对应的operatorListener,将结果回调给客户
                        val operatorListener =
                            getOperatorListener(instanceId, Constant.SYSTEM_CLIP_BOARD)
                        operatorListener?.apply {
                            operatorResult(
                                instanceId,
                                result.code,
                                result.message
                            )
                            removeOperatorListener(instanceId, Constant.SYSTEM_CLIP_BOARD)
                        }
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}sysPreviewStart connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "", " connect onClose:$reason")
                    }
                    isSendResult = false
                    //cancelTimeHeartBeatSend()
                    mOperatorInstanceIdMap.clear()
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}sysPreviewStart onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let {
                        WebSocketManager.getInstance().closeConnect(it)
                    }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "", "connect onError:${ex.message}")
                    }
                    isSendResult = false

                   // cancelTimeHeartBeatSend()
                    mOperatorInstanceIdMap.clear()
                }

                override fun onMessage(bytes: ByteBuffer) {
                    while (true) {
                        //每个数据包最少7个字节
                        if (bytes.remaining() > 7) {
                            val beginIndex = bytes.position()
                            //记录本次消息读取的开始位置，如果无法读取完整数据就重置到此位置
                            bytes.mark()
                            //读取一个字节
                            val head = bytes.get()

                            // XLogUtil.d("onMessage 预览图数据 head :" + head.toHexString())
                            if (head == Constant.HEAD) {
                                val length = bytes.int
                                //帧类型
                                val type = bytes.get()

                                //读取帧数据
                                var bytesToRead = ByteArray(length)
                                bytes.get(bytesToRead)

                                //帧尾
                                val tail = bytes.get()
                                if (tail != Constant.TAIL) {
                                    //帧尾错误，读取位置+1重置，继续尝试读取
                                    bytes.reset()
                                    //bytes.get(1)
                                    bytes.position(beginIndex + 1)
                                    continue
                                }

                                //图片数据
                                if (type == Constant.PICTURE_TYPE) {
                                    XLogUtil.d("${TAG}收到完整图片数据:")
//                                    val stitchBmp =
//                                        Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888)
//
//                                    val pictureByteBuffer=ByteBuffer.wrap(bytesToRead)
//                                    pictureByteBuffer.rewind()
//                                    stitchBmp.copyPixelsFromBuffer(pictureByteBuffer)

                                    val bitmap = BitmapFactory.decodeByteArray(
                                        bytesToRead,
                                        0,
                                        bytesToRead.size
                                    )

                                    listener.previewData(bitmap)
                                } else if (type == Constant.CONTROL_TYPE) {
                                    XLogUtil.d("${TAG}收到控制数据:")
                                }
                            } else {
                                XLogUtil.e("${TAG_ERROR}预览图数据 读取帧头异常 ==> head:$head")
                            }
                        } else {
                            return
                        }
                    }
                }
            })

    }


    /**
     * 开启心跳发送定时器
     */
    private fun openHeartBeatSend(client: WebSocketClient) {
        try {
            //每隔30s发送一次心跳
            mTimerSendHeartBeat = Timer()
            mTimerSendHeartBeat?.schedule(object : TimerTask() {
                override fun run() {
                    sendHeartBeatToServer(client)
                }
            }, (1000 * 30).toLong(), (1000 * 30).toLong())
        } catch (e: Exception) {
            XLogUtil.e("${TAG_ERROR}openHeartBeatSend Exception " + e.message)
        }
    }

    /**
     * 取消心跳发送定时器
     */
    private fun cancelTimeHeartBeatSend() {
        if (mTimerSendHeartBeat != null) {
            XLogUtil.d("${TAG}closeHeartBeatSend")
            mTimerSendHeartBeat!!.cancel()
            mTimerSendHeartBeat = null
        }
    }


    /**
     * 发送心跳给服务端
     */
    private fun sendHeartBeatToServer(client: WebSocketClient) {
        val messageInfo = MessageInfo2(
            RequestIdCreatUtil.creatId(Constant.HEART_BEAT),
            Constant.HEART_BEAT
        )

        client?.let {
            //更新Pong time 不然服务端没发心跳,会断联
            val webSocket = it.connection
            var webSocketImpl = webSocket as WebSocketImpl
            webSocketImpl.updateLastPong()

            WebSocketManager.getInstance()
                .sendMessage(it, JSONObject.toJSONString(messageInfo))
        }
    }


    /**
     *停止预览图推流
     */
    fun sysPreviewStop(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null
       // cancelTimeHeartBeatSend()


        //如果已经连接，拿到连接发送停止预览图指令
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val messageInfo = MessageInfo2(
                    RequestIdCreatUtil.creatId(Constant.SYSTEM_PREVIEW_STOP),
                    Constant.SYSTEM_PREVIEW_STOP,
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                // Thread.sleep(300)
                //发送完停止预览图指令后，关闭连接
                // clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
            }
            return
        }



        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val messageInfo = MessageInfo2(
                                RequestIdCreatUtil.creatId(Constant.SYSTEM_PREVIEW_STOP),
                                Constant.SYSTEM_PREVIEW_STOP,
                            )
                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                            clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}sysPreviewStop sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYSTEM_PREVIEW_STOP, message)
                    XLogUtil.d(
                        "${TAG}sysPreviewStop 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}sysPreviewStop connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false

                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}sysPreviewStop onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false

                }
            })
    }


    /**
     *虚拟定位
     * ● longitude：经度，类型为 string。
     * ● latitude：纬度，类型为 string
     */
    fun virtualLocation(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        longitude: String,
        latitude: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val virtualLocation = ReqVirtualLocation(longitude, latitude)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.VIRTUAL_LOCATION),
                    Constant.VIRTUAL_LOCATION,
                    virtualLocation
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.VIRTUAL_LOCATION, listener)
            }
            return
        }


        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val virtualLocation = ReqVirtualLocation(longitude, latitude)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.VIRTUAL_LOCATION),
                                Constant.VIRTUAL_LOCATION,
                                virtualLocation
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}virtualLocation sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.VIRTUAL_LOCATION, message)
                    XLogUtil.d(
                        "${TAG}virtualLocation 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}virtualLocation connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false

                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}virtualLocation onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false

                }
            })

    }


    /**
     * 剪切板
     */
    fun clipBoard(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        content: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {

                val clipboard = ReqClipboard(content)
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.SYSTEM_CLIP_BOARD),
                    Constant.SYSTEM_CLIP_BOARD,
                    clipboard
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.SYSTEM_CLIP_BOARD, listener)
            }
            return
        }




        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val clipboard = ReqClipboard(content)
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.SYSTEM_CLIP_BOARD),
                                Constant.SYSTEM_CLIP_BOARD,
                                clipboard
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}clipBoard sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYSTEM_CLIP_BOARD, message)
                    XLogUtil.d(
                        "${TAG}clipBoard 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }

                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}clipBoard connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false

                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG}clipBoard onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 设置分辨率
     * ● width：宽，类型为 int
     * ● height：高，类型为 int
     */
    fun sysResolution(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        width: String,
        height: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val sysResolution = ReqSysResolution(width.toInt(), height.toInt())
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.SYSTEM_RESOLUTION),
                    Constant.SYSTEM_RESOLUTION,
                    sysResolution
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.SYSTEM_RESOLUTION, listener)
            }
            return
        }


        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val sysResolution = ReqSysResolution(width.toInt(), height.toInt())
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.SYSTEM_RESOLUTION),
                                Constant.SYSTEM_RESOLUTION,
                                sysResolution
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}syResolution sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYSTEM_RESOLUTION, message)
                    XLogUtil.d(
                        "${TAG}syResolution 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}syResolution connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}syResolution onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    /**
     * 设置DPI
     */
    fun sysDpi(
        instanceId: String,
        wsAddress: String,
        ip: String,
        token: String,
        dpi: String,
        listener: OperatorListener
    ) {
        var isSendResult = true
        var webSocketClient: WebSocketClient
        var clientConnect: ClientConnect? = null


        //如果已经连接，拿到连接发送请求----在开启预览图时，就是已连接状态
        clientConnect = WebSocketManager.getInstance().getClientConnect(instanceId)
        if (clientConnect != null) {
            webSocketClient = clientConnect!!.client
            webSocketClient?.apply {
                val sysDpi = ReqSysDpi(dpi.toInt())
                val messageInfo = MessageInfo(
                    RequestIdCreatUtil.creatId(Constant.SYSTEM_DPI),
                    Constant.SYSTEM_DPI,
                    sysDpi
                )

                WebSocketManager.getInstance()
                    .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))

                //将listener存储起来，后面将消息结果回调给上层
                addOperatorListener(instanceId, Constant.SYSTEM_DPI, listener)
            }
            return
        }

        clientConnect = WebSocketManager.getInstance()
            .addClient(instanceId, wsAddress, ip, token, getDeviceId(),object : WebSocketConnectListener {
                override fun onOpen(handshakedata: ServerHandshake) {
                    if (clientConnect != null) {
                        webSocketClient = clientConnect!!.client
                        webSocketClient?.apply {
                            val sysDpi = ReqSysDpi(dpi.toInt())
                            val messageInfo = MessageInfo(
                                RequestIdCreatUtil.creatId(Constant.SYSTEM_DPI),
                                Constant.SYSTEM_DPI,
                                sysDpi
                            )

                            WebSocketManager.getInstance()
                                .sendMessage(webSocketClient, JSONObject.toJSONString(messageInfo))
                        }
                    } else {
                        XLogUtil.e("${TAG_ERROR}sysDpi sendMessage fail,clientConnect==null,,,instanceId=$instanceId,,,ip=$ip")
                    }
                }

                override fun onRecMessage(message: String) {
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    //请求返回结果
                    var result = parseMessage(instanceId, Constant.SYSTEM_DPI, message)
                    XLogUtil.d(
                        "${TAG}sysDpi 收到服务端返回 result:{${
                            JSONObject.toJSONString(
                                result
                            )
                        }},,,,,message:$message"
                    )
                    if (isSendResult) {
                        listener.operatorResult(instanceId, result.code, result.message)
                    }

                    isSendResult = false
                }

                override fun onClose(code: Int, reason: String, remote: Boolean) {
                    XLogUtil.d("${TAG}sysDpi connect onClose code:$code,,,,,reason:$reason,,,remote:$remote,,,instanceId:$instanceId,,,ip:$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, " connect onClose:$reason")
                    }
                    isSendResult = false
                }

                override fun onError(ex: Exception) {
                    XLogUtil.e("${TAG_ERROR}sysDpi onError Exception:${ex.message},,,,,,instanceId$instanceId,,,,,,ip$ip")
                    clientConnect?.let { WebSocketManager.getInstance().closeConnect(it) }
                    if (isSendResult) {
                        listener.operatorResult(instanceId, -1, "connect onError:${ex.message}")
                    }
                    isSendResult = false
                }
            })

    }


    fun parseMessage(instanceId: String, doOperate: String, message: String): MessageResult {
        try {
            val jsonObject = JSON.parseObject(message)
            val request_id = jsonObject.getString("request_id")
            val code = jsonObject.getInteger("code")
            val message = jsonObject.getString("message")
            val type = jsonObject.getString("type")

            //JSON.parseObject(message, MessageResult::class.java) kotlin中直接反系列化会报错
            return MessageResult(request_id, code, type, message)
        } catch (e: Exception) {
            XLogUtil.e("${TAG_ERROR}$doOperate parseMessage exception,instanceId:$instanceId,,,message:${e.message}")
        }

        return MessageResult(instanceId, -1, doOperate, "parseMessage exception")
    }


    /**
     * 获取SDK版本号
     */
    public fun getSdkVersion(): String {
        return Constant.VC_SDK_VERSION
    }


    /**
     * key 值格式，例如：Constant.SYSTEM_CLIP_BOARD
     */
    private fun addOperatorListener(instanceId: String, key: String, listener: OperatorListener) {
        var operatorListenerMap = mOperatorInstanceIdMap[instanceId]

        if (operatorListenerMap == null) {
            operatorListenerMap = ConcurrentHashMap<String, OperatorListener>()
        }

        operatorListenerMap[key] = listener
        mOperatorInstanceIdMap[instanceId] = operatorListenerMap
    }


    /**
     * 找到实例中的接口操作operatorListener,并删除
     */
    private fun removeOperatorListener(instanceId: String, key: String) {
        var operatorListenerMap = mOperatorInstanceIdMap[instanceId]
        operatorListenerMap?.remove(key)
    }


    /**
     * 获取 OperatorListener
     */
    private fun getOperatorListener(instanceId: String, key: String): OperatorListener? {
        var operatorListenerMap = mOperatorInstanceIdMap[instanceId]
        if (operatorListenerMap != null) {
            val operatorListener = operatorListenerMap[key]
            if (operatorListener != null) {
                return operatorListener
            }
        }
        return null
    }


    fun setDeviceId(deviceId:String){
        if(deviceId.isNotEmpty()){
            mDeviceId=deviceId
        }
    }

    fun getDeviceId():String{
        return mDeviceId
    }

}


